package fi.internetix.quercus;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.caucho.quercus.annotation.Optional;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.StringValue;

/**
 * PHP functions implemented from the mail module
 */
public class MailModule extends com.caucho.quercus.lib.mail.MailModule {
  
  private static final Logger log = Logger.getLogger(MailModule.class.getName());
  
  public static boolean mail(Env env, String to, String subject, StringValue message, @Optional String additionalHeaders, @Optional String additionalParameters) {

    HashMap<String, String> headers = splitHeaders(additionalHeaders);
    
    String mailFrom = null;

    StringValue user = null;

    if (headers.get("from") != null)
      user = env.createString(headers.get("from"));

    if (user == null)
      user = env.getIni("sendmail_from");

    if (user != null && !user.toString().equals("")) {
      String userString = user.toString();

      mailFrom = userString;
    } else if (System.getProperty("mail.from") != null)
      mailFrom = System.getProperty("mail.from");
    else {
      try {
        InetAddress addr = InetAddress.getLocalHost();

        String email = (System.getProperty("user.name") + "@" + addr.getHostName());

        int index = email.indexOf('@');

        // for certain windows smtp servers
        if (email.indexOf('.', index) < 0)
          email += ".com";

        mailFrom = email;
      } catch (Exception e) {
        log.log(Level.FINER, e.toString(), e);
      }
    }

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    try {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(mailFrom));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      msg.setSubject(subject);
      msg.setText(message.toString());
      Transport.send(msg);

    } catch (AddressException e) {
      log.log(Level.SEVERE, "Mailing failed", e);
    } catch (MessagingException e) {
      log.log(Level.SEVERE, "Mailing failed", e);
    }
    return true;
  }

  @SuppressWarnings("unchecked")
  private static HashMap<String, String> splitHeaders(String headers) {
    try {
      Method method = com.caucho.quercus.lib.mail.MailModule.class.getDeclaredMethod("splitHeaders", new Class<?>[] { String.class });
      method.setAccessible(true);
      return (HashMap<String, String>) method.invoke(null, new Object[] { headers });
    } catch (SecurityException e) {
      e.printStackTrace();      
    } catch (NoSuchMethodException e) {
    } catch (IllegalArgumentException e) {
    } catch (IllegalAccessException e) {
    } catch (InvocationTargetException e) {
    }

    return null;
  }

}